/**
/**
 * Copyright (c) 2022,TravelSky. 
 * All Rights Reserved.
 * TravelSky CONFIDENTIAL
 * 
 * Project Name:ddserver
 * Package Name:com.asb.controller
 * File Name:IndexController.java
 * Date:2022年3月17日 下午12:04:11
 * 
 */
package com.asb.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.asb.model.vo.ResultVo;
import com.asb.model.vo.UserVo;
import com.asb.service.NotifyDingTalkService;
import com.asb.service.UserDingTalkService;
import com.asb.utils.AccessUtil;
import com.asb.utils.HttpTools;
import com.asb.utils.JsonUtil;
import com.asb.utils.Strings;
import com.asb.vo.DingTalkTempFileVO;
import com.jfinal.aop.Inject;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.ext.cors.EnableCORS;
import com.jfinal.kit.Ret;
import com.jfinal.upload.UploadFile;
import com.taobao.api.ApiException;

import cn.hutool.core.util.StrUtil;

/**
 * ClassName: IndexController <br/>
 * Description: TODO <br/>
 * Date: 2022年3月17日 下午12:04:11 <br/>
 * <br/>
 * 
 * @author 1(邮箱)
 * 
 *         修改记录
 * @version 产品版本信息 yyyy-mm-dd 姓名(邮箱) 修改信息<br/>
 * 
 */

@Path("/dingtalk/inner")
//@Before(CorsInterceptor.class)
@EnableCORS
public class DingTalkController extends Controller {

	public static Logger log = Logger.getLogger(DingTalkController.class);

	private final String PATH_MAPPING = "/";

	@Inject
	UserDingTalkService userService;

	@Inject
	NotifyDingTalkService notifyService;

	/**
	 * 钉钉OA审批、通知接口(暴露给对方的接口)
	 */
	@ActionKey(PATH_MAPPING + "interface/notify")
	public void handle() {
		try {
			String id = this.getPara("id");
			this.renderJson(notifyService.notify(id, HttpTools.readBody(getRequest())));
		} catch (Exception e) {
			// e.printStackTrace();
			log.error("", e);
			Map<String, String> resultMap = new HashMap<>();
			resultMap.put("code", "9999");
			resultMap.put("msg", "系统错误：请检查参数子节点是否为空");
			resultMap.put("taskid", "");
			this.renderJson(JSON.toJSONString(resultMap));
		}
	}

	/**
	 * 钉钉-上传文件
	 */
	@ActionKey(PATH_MAPPING + "inner/file/upload")
	public void uploadFile() {
		try {
			List<UploadFile> upfileList = this.getFiles();
			Ret resJson = Ret.create();
			if (upfileList == null || upfileList.size() <= 0) {
				resJson.set("code", -1);
				resJson.set("msg", "出现错误,上传文件为空");
				renderJson(resJson);
				return;
			}
			String id = this.getPara("id");
			String tempid = this.getPara("tempid");
			if (Strings.isNullOrEmpty(id)) {
				// 临时上传
				List<String> names = this.uploadFileTemp(tempid, upfileList);
				resJson.set("code", 0);
				resJson.set("msg", "sucess");
				resJson.set("data", names);
				renderJson(resJson);

			} else {
				List<String> names = new ArrayList<>();
				// 接口发送
				for (UploadFile upfile : upfileList) {
					File file = upfile.getFile();
					String filename = file.getName();
					names.add(filename);
					String userName = this.getPara("username");
					if (filename != null && !filename.equals("")) {
						notifyService.postInteface(id, userName, file, filename);
					}
				}
				resJson.set("code", 0);
				resJson.set("msg", "sucess");
				resJson.set("data", names);
				renderJson(resJson);
			}
		} catch (Exception e) {
			// e.printStackTrace();
			log.error("", e);
			Ret resJson = Ret.create();
			resJson.set("code", -9);
			resJson.set("msg", "出现错误,系统异常");
			renderJson(resJson);
		}
	}

	/**
	 * 钉钉-删除文件
	 */
	@ActionKey(PATH_MAPPING + "inner/file/delete")
	public void deleteFile() {
		String id = this.getPara("id");
		String filename = this.getPara("filename");
		String tempid = this.getPara("tempid");
		int result = 0;
		try {
			if (Strings.isNullOrEmpty(id)) {
				result = notifyService.deleteFileTemp(tempid, filename);
			} else {
				result = notifyService.deleteFile(id, filename);
			}

			if (result == -1) {
				Ret resJson = Ret.create();
				resJson.set("code", -1);
				resJson.set("msg", "删除的id，无法和用户匹配");
				renderJson(resJson);
			}
			if (result == -2) {
				Ret resJson = Ret.create();
				resJson.set("code", -2);
				resJson.set("msg", "出现错误,附件删除异常");
				renderJson(resJson);
			}
			if (result == 0) {
				Ret resJson = Ret.create();
				resJson.set("code", 200);
				resJson.set("msg", "success");
				renderJson(resJson);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			log.error("", e);
			Ret resJson = Ret.create();
			resJson.set("code", -9);
			resJson.set("msg", "出现错误,系统异常");
			renderJson(resJson);
		}

	}

	/**
	 * 钉钉-上传临时文件
	 */
	private List<String> uploadFileTemp(String tempid, List<UploadFile> upfileList) {
		List<String> names = new ArrayList<>();
		for (UploadFile upfile : upfileList) {
			File file = upfile.getFile();
			String oldFileName = file.getName();
			names.add(oldFileName);
			String randomStr = Strings.simpleUUID();
			String newFileName = randomStr + oldFileName.substring(oldFileName.lastIndexOf("."));
			File saveFile = new File(HttpTools.UPLOAD_TEMP_URL, newFileName);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			InputStream in = null;
			FileOutputStream out = null;
			try {
				in = new FileInputStream(file);
				;
				/* 保存 */
				out = new FileOutputStream(saveFile);
				byte[] buf = new byte[4096];
				int readLength = -1;
				while ((readLength = in.read(buf)) != -1) {
					out.write(buf);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				log.error("", e);
			} finally {
				try {
					out.flush();
					out.close();
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					// e.printStackTrace();
					log.error("", e);
				}
			}
			DingTalkTempFileVO vo = new DingTalkTempFileVO();
			vo.setId(tempid);
			vo.setFile_name(oldFileName);
			vo.setTemp_name(newFileName);
			vo.setPath(HttpTools.UPLOAD_TEMP_URL);
			notifyService.saveTempFile(vo);
		}

		return names;
	}

	/*
	 * @ActionKey(PATH_MAPPING + "inner/temp/delete") public void deleteFileTemp() {
	 * String id = this.getPara("id"); int result = 0; try { result =
	 * notifyService.deleteFileTemp(id); if (result == -1) { Ret resJson =
	 * Ret.create(); resJson.set("code", -1); resJson.set("msg", "删除的id，无法和用户匹配");
	 * renderJson(resJson); } if (result == -2) { Ret resJson = Ret.create();
	 * resJson.set("code", -2); resJson.set("msg", "出现错误,附件删除异常");
	 * renderJson(resJson); } if (result == 0) { Ret resJson = Ret.create();
	 * resJson.set("code", 200); resJson.set("msg", "success"); renderJson(resJson);
	 * } } catch (Exception e) { // TODO Auto-generated catch block //
	 * e.printStackTrace(); log.error(e); Ret resJson = Ret.create();
	 * resJson.set("code", -9); resJson.set("msg", "出现错误,系统异常");
	 * renderJson(resJson); }
	 * 
	 * }
	 */

	/**
	 * 钉钉-临时文件发送通知
	 */
	@ActionKey(PATH_MAPPING + "inner/temp/notice")
	public void noticeTemp() {
		String id = this.getPara("id");
		String tempid = this.getPara("tempid");
		String username = this.getPara("username");
		String filetype = this.getPara("filetype");
		String fullName = username + "." + filetype;
		List<String> list = notifyService.sendFiles(id, tempid, fullName);
		Ret resJson = Ret.create();
		resJson.set("code", 0);
		resJson.set("msg", "success");
		resJson.set("data", list);
		renderJson(resJson);
	}

	/**
	 * 钉钉-免密登录
	 * 
	 * @throws ApiException
	 */
	// @ActionKey(PATH_MAPPING + "inner/login")
	public void login() throws ApiException {

		String authCode = this.getPara("authCode");
		String userid = this.getPara("userid");

		Ret resJson = Ret.create();
		if (StrUtil.isBlankIfStr(userid)) {
			if (Strings.isNullOrEmpty(authCode)) {
				resJson.set("code", -1);
				resJson.set("msg", "authCode获取为空");
				renderJson(resJson);
				return;
			} else {
				userid = userService.getUserIdByAuthCode(authCode);
			}
		}

		List<UserVo> list = userService.userLoginByUserid(userid);
		if (list == null) {
			renderJson(new ResultVo<List<UserVo>>().setCode(400).setMsg("authCode无法获取到用户信息"));
		} else {
			for (UserVo v : list) {
				v.setUserid(userid);
			}
			renderJson(new ResultVo<List<UserVo>>().setData(list));
		}
	}

	/************************************
	 * 临时接口
	 ****************************************************/

	/**
	 * 临时-模拟返回
	 */
	@ActionKey(PATH_MAPPING + "flie/result")
	public void flieResult() throws ApiException {
		System.out.println("abccba");
		Ret resJson = Ret.create();
		resJson.set("status", 0);
		resJson.set("message", "success");
		renderJson(resJson);

		try {
			StringBuffer strBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(this.getRequest().getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line).append("\n");
			}
			String res = strBuf.toString();
			System.out.println(res);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			log.error("", e);
		}

	}

	/**
	 * 临时-手动通知
	 */
	@ActionKey(PATH_MAPPING + "door")
	public void door() {

		String mobile = this.getPara("mobile");
		String kb = this.getPara("kb");
		String taskid = this.getPara("taskid");

		String jsonString = userService.getUserIdByMobile(mobile);

		String userId = "";
		String unionid = "";

		try {
			/**
			 * 获取用户信息 userid unionid
			 */
			Map<String, Object> map1 = JsonUtil.toRes(jsonString);
			userId = String.valueOf(map1.get("userid"));
			String detailStr = userService.getUserDetail(userId);
			Map<String, Object> map2 = JsonUtil.toRes(detailStr);
			unionid = String.valueOf(map2.get("unionid"));

			// 执行人或者抄送人
			if ("1".equals(kb)) {
				// 发送通知
				String result = notifyService.sendConversation(userId, new HashMap<String, Object>());
				log.info("通知信息: " + result);
				System.out.println("通知信息: " + result);
				/*
				 * // 发送待办 notifyService.sendTask(unionid);
				 */
			}

			// 领导审核
			if ("2".equals(kb)) {
				String result = notifyService.sendProcess(userId, userId, new HashMap<String, Object>());
				log.info("审批信息: " + result);
				System.out.println("审批信息: " + result);
			}

			// 撤销审批
			if ("3".equals(kb)) {
				String result = notifyService.terminateProcess(userId, taskid);
				log.info("撤销审批信息: " + result);
				System.out.println("撤销审批信息: " + result);
			}

		} catch (Exception e) {
			// e.printStackTrace();
			log.error("", e);
		}

		this.renderJson("result", "success");
	}

	/**
	 * 临时-user信息
	 */
	@ActionKey(PATH_MAPPING + "test")
	public void test() throws ApiException {

		String token = AccessUtil.getAccess_token();

		String userId = userService.getAllUsers(1L);

		System.out.println(token);

		System.out.println(userId);

		this.renderJson("result", token + " : " + userId);
	}

	public void address() {
		String key = this.getPara(0);
		if ("getuserid".equals(key)) {
			Long deptid = this.getParaToLong("id");
			String json = userService.getAllUsers(deptid);
			renderJson(new ResultVo<List<String>>().setData(JSON.parseObject(json).getJSONObject("result")
					.getJSONArray("userid_list").toJavaList(String.class)));
		}
	}

}
